<?php
namespace App\Domain;

use App\Common\Functions;
use Platform\Model\File as FileModel;
use PhalApi\Exception\BadRequestException;

class File extends Functions{
    // 上传文件方法
    public function uplodFile($fileInfo){
        $model = new FileModel();
        $rs = array('code' => 0, 'url' => '');
        $tmpName = $fileInfo['tmp_name'];

        $name = md5($fileInfo['name'] . $_SERVER['REQUEST_TIME']);
        $ext = strrchr($fileInfo['name'], '.');
//        $savePath=\PhalApi\DI()->config->get('app.CommonParams.savePath');
        // $uploadFolder = $savePath.'/uploads/MaterialsFiles/';
        $uploadFolder = sprintf('%s/public/uploads/Files/', API_ROOT);
        if (!is_dir($uploadFolder)) {
            mkdir($uploadFolder, 0777);
        }
        $imgPath = $uploadFolder .  $name . $ext;
        if (move_uploaded_file($tmpName, $imgPath)) {
//            $serverName=\PhalApi\DI()->config->get('app.CommonParams.uploadHost');
            $fullUrl=sprintf('http://%s/uploads/Files/%s%s', $_SERVER['SERVER_NAME'], $name, $ext);
            $getCode=$this->getEncoding('FILE');
            $insertData=array();
            $insertData['att_save_code']=$getCode;
            $insertData['att_original_name']=$fileInfo['name'];
            $insertData['att_upload_path']=$fullUrl;
            $insertData['att_type']=$ext;
            $insertData['att_size']=$fileInfo['size'];
            // 获取添加人员信息
            $insertData = $this->selfAddFields($insertData);
            if($model->insert($insertData) === false){
                throw new BadRequestException('上传失败！');
            }
            $rs['code'] = 1;
            $rs['url'] =$fullUrl;
            $rs['fileName'] = $getCode;
            $rs['oldFileName'] = $fileInfo['name'];
            $rs['att_type']=$getCode.str_replace('.', '', $ext);
        }
        //更新用户头像

        return $rs;
    }
}